import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:jtsell_app/entity/mall_goods_entity.dart';
import 'package:jtsell_app/routes/routes.dart';
import 'package:jtsell_app/widget/loading_widget.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../provider/main_category_model.dart';
import '../entity/category_entity.dart';
import '../network/http_dispense.dart';
import '../provider/child_category_model.dart';

class CategoryPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<ChildCategoryModel>.value(value: childCategoryModelDef),
        StreamProvider<List<MallGoodsEntity>>.controller(
          builder: (BuildContext context) => childCategoryModelDef.streamCtrl,
        ),
      ],
      child: CategoryWidget(),
    );
  }
}

///
/// 页面总布局
///
class CategoryWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("商品分类"),
      ),
      body: Row(
        children: <Widget>[
          LeftCategoryWidget(),
          Expanded(
              flex: 1,
              child: Column(
                children: <Widget>[
                  TopCategoryWidget(),
                  Expanded(
                    child: BottomGoodsWidget(),
                  )
                ],
              )),
        ],
      ),
    );
  }
}

///
/// 左侧导航栏
///
class LeftCategoryWidget extends StatefulWidget {
  @override
  _LeftCategoryWidgetState createState() => _LeftCategoryWidgetState();
}

class _LeftCategoryWidgetState extends State<LeftCategoryWidget> {
  final Stream<List<CategoryEntity>> _mainCategoryStream =
      Stream.fromFuture(HttpDispense.getCategoryList()).asBroadcastStream();
  int _lastSelectIndex = 0;

  MainCategoryModel mainCategoryModel;
  ChildCategoryModel childCategoryModel;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((callback) {
      mainCategoryModel = Provider.of<MainCategoryModel>(context);
      childCategoryModel = Provider.of<ChildCategoryModel>(context);
    });

    ///用于监听初始化完成结果，加载子分类信息
    //_mainCategoryStream = Stream.fromFuture(HttpDispense.getCategoryList()).asBroadcastStream();
    _mainCategoryStream.listen((List<CategoryEntity> list) {
      int index = 0;

      ///首次加载 初始化子分类
      mainCategoryModel.setCurrentIndex(index);
      childCategoryModel.setChildCategoryList(list[index].bxMallSubDto);

      childCategoryModel.setCurrentChildIndex(0);
      childCategoryModel.setChildCategory(childCategoryModel.childCategoryList[0]);
    });
  }

  ///加载状态提示
  Widget _getHintWidget(String hintText) {
    return Center(child: Text("$hintText"));
  }

  ///获取分类项
  Widget _getCategoryItem(BuildContext context, CategoryEntity item, int index) {
    bool isSelectItem = (_lastSelectIndex == index);

    return InkWell(
      child: Container(
        height: ScreenUtil().setHeight(150),
        child: Center(
          child: Text(
            "${item?.mallCategoryName}",
            maxLines: 1,
            textAlign: TextAlign.center,
          ),
        ),
        decoration: BoxDecoration(color: isSelectItem ? Colors.black12 : Colors.white),
      ),
      onTap: () {
        ///过滤重复点击
        if (_lastSelectIndex == index) {
          return;
        }

        ///更新点击的主分类索引
        mainCategoryModel.setCurrentIndex(index);

//       ///更新主分类对象的子分类的的集合
//        childCategoryModel.setChildCategoryList(item.bxMallSubDto);
//
//        ///点击主分类时,重新拉取商品信息
//        ///由于在 mainCategoryModel.setChildCategory 添加了全部类别
//        ///所以这个使用mainCategoryModel.childCategory[0]获取分类
//        childCategoryModel.setChildCategoryAndIndex(childCategoryModel.childCategoryList[0],0);

        ///点击主分类时,清空子分类的索引
        //childCategoryModel.setCurrentChildIndex(0);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<CategoryEntity>>(
        stream: _mainCategoryStream,
        builder: (BuildContext context, AsyncSnapshot<List<CategoryEntity>> snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            return _getHintWidget("正在加载...");
          }
          if (snapshot.hasError) {
            return _getHintWidget("加载错误");
          }
          List<CategoryEntity> categoryList = snapshot.data;
          if (categoryList == null || categoryList.isEmpty) {
            return _getHintWidget("暂无数据");
          }
          return Container(
            width: ScreenUtil().setWidth(200),
            child: Consumer<MainCategoryModel>(
                builder: (BuildContext context, MainCategoryModel value, Widget child) {
              ///如果将要切换的分类和之前的不一样
              ///则重置子分类列表
              if (_lastSelectIndex != value.currentIndex) {
                _lastSelectIndex = value.currentIndex;

                ///不同类别时，类似于点击事件
                childCategoryModel
                    .setChildCategoryList(categoryList[_lastSelectIndex].bxMallSubDto);

                childCategoryModel.setChildCategoryAndIndex(childCategoryModel
                    .childCategoryList[0],0);
              }

              return ListView.builder(
                  itemCount: categoryList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      child: _getCategoryItem(context, categoryList[index], index),
                    );
                  });
            }),
          );
        });
  }
}

///
/// 顶部子导航栏
///
class TopCategoryWidget extends StatelessWidget {
  int _currentChildIndex = 0;
  ChildCategoryModel childCategoryModel;
  ///获取分类项
  Widget _getChildCategoryItem(BuildContext context, CategoryBxmallsubdto item, int index) {
    bool isSelectItem = (_currentChildIndex == index);

    return InkWell(
      child: Container(
        margin: EdgeInsets.only(left: ScreenUtil().setWidth(15), right: ScreenUtil().setWidth(15)),
        child: Center(
          child: Text(
            "${item?.mallSubName}",
            maxLines: 1,
            textAlign: TextAlign.center,
            style: TextStyle(
                color: isSelectItem ? Theme.of(context).primaryColor : Colors.black,
                fontSize: ScreenUtil().setSp(45)),
          ),
        ),
      ),
      onTap: () {
        ///过滤重复点击
        if (_currentChildIndex == index) {
          return;
        }

        ///设置子类点击的索引
        childCategoryModel.setCurrentChildIndex(index);

        ///设置当前点击的子类
        childCategoryModel.setChildCategory(item);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    childCategoryModel=Provider.of<ChildCategoryModel>(context);

    return Consumer2<MainCategoryModel, ChildCategoryModel>(builder: (BuildContext context,
        MainCategoryModel model, ChildCategoryModel childModel, Widget child) {
      ///获取点击菜单的子类
      List<CategoryBxmallsubdto> childCategoryList = childModel.childCategoryList;

      ///接收当前点击的子类
      _currentChildIndex = childModel.currentChildIndex;

      if (childCategoryList == null || childCategoryList.isEmpty) {
        return Center(child: Text("暂无数据"));
      }

      return Container(
        decoration: BoxDecoration(color: Colors.white),
        height: ScreenUtil().setHeight(100),
        child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: childCategoryList.length,
            itemBuilder: (BuildContext context, int index) {
              return _getChildCategoryItem(context, childCategoryList[index], index);
            }),
      );
    });
  }
}

///
/// 底部商品列表
///
class BottomGoodsWidget extends StatefulWidget {
  @override
  _BottomGoodsWidgetState createState() => _BottomGoodsWidgetState();
}

class _BottomGoodsWidgetState extends State<BottomGoodsWidget> {
  GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>();

  ///当前加载的页数
  int _currentPageIndex = 1;

  ///当前选中的子分类
  CategoryBxmallsubdto _bxmallsubdto;

  ///子分类所对应的已经在加载的所有商品列表
  List<MallGoodsEntity> _mallGoodsList = List();

  @override
  void initState() {
    super.initState();
  }

  ///
  /// 下拉加载更多
  ///
  Future _loadMoreHandler() {
    if (_bxmallsubdto == null) {
      return Future(() {});
    }

    Map<String, dynamic> data = {
      "categoryId": _bxmallsubdto.mallCategoryId,
      "categorySubId": _bxmallsubdto.mallSubId,
      "page": _currentPageIndex
    };

    return HttpDispense.getMallGoodsListByCategory(data).then((newList) {
      _currentPageIndex++;

      childCategoryModelDef.streamCtrl.sink.add(newList);
      return null;
    });
  }

  Widget _listWidgetItem(MallGoodsEntity mallGoods) {
    return InkWell(
        onTap: () {
          Routes.getInstance().pushGoodsDetailPage(context, mallGoods.goodsId);
        },
        child: Container(
          padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
          child: Row(
            children: <Widget>[
              _goodsImage(mallGoods.image),
              Column(
                children: <Widget>[
                  _goodsName(mallGoods.goodsName),
                  _goodsPrice(mallGoods.presentPrice, mallGoods.oriPrice)
                ],
              )
            ],
          ),
        ));
  }

  //商品图片
  Widget _goodsImage(String imageUrl) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(imageUrl),
    );
  }

  //商品名称方法
  Widget _goodsName(String goodsName) {
    return Container(
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370),
      child: Text(
        goodsName,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(36)),
      ),
    );
  }

  //商品价格方法
  Widget _goodsPrice(double presentPrice, double oriPrice) {
    return Container(
        margin: EdgeInsets.only(top: 20.0),
        width: ScreenUtil().setWidth(370),
        child: Row(children: <Widget>[
          Text(
            '价格:￥$presentPrice',
            style:
                TextStyle(color: Theme.of(context).primaryColor, fontSize: ScreenUtil().setSp(36)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Text(
            '￥$oriPrice',
            style: TextStyle(
                color: Colors.black26,
                decoration: TextDecoration.lineThrough,
                fontSize: ScreenUtil().setSp(36)),
          )
        ]));
  }

  @override
  Widget build(BuildContext context) {
    return Consumer3<MainCategoryModel, ChildCategoryModel, List<MallGoodsEntity>>(builder:
        (BuildContext context,
            MainCategoryModel mainCategoryModel,
            ChildCategoryModel childCategoryModel,
            List<MallGoodsEntity> mallGoodsList,
            Widget child) {
      ///暂无数据
      if (childCategoryModel.bxmallsubdto == null) {
        return Center(child: Text("暂无数据"));
      }

      if (_bxmallsubdto == childCategoryModel.bxmallsubdto) {
        print("相同类别");

        ///添加集合到所有数据
        if (mallGoodsList != null) {
          _mallGoodsList.addAll(mallGoodsList);
        }
      } else {
        print("不同类别");

        ///不同类型重置所有数据
        _currentPageIndex = 1;
        _mallGoodsList.clear();
        _bxmallsubdto = childCategoryModel.bxmallsubdto;

        ///切换类型时重新加载数据
        _loadMoreHandler();
        return LoadingWidget();
      }

      ///列表为空时返回提示
      if (_mallGoodsList.isEmpty) {
        return Center(child: Text("暂无数据"));
      }

      return EasyRefresh(
        autoLoad: true,
        loadMore: _loadMoreHandler,
        refreshFooter: ClassicsFooter(
          key: _footerKey,
          loadHeight: ScreenUtil().setHeight(150),
          showMore: true,
          noMoreText: '暂无数据',
          moreInfo: '加载中',
          loadReadyText: '上拉加载....',
          loadingText: "加载中",
          loadedText: "加载完成",
          loadText: "上拉加载",
          textColor: Theme.of(context).primaryColor,
          moreInfoColor: Theme.of(context).primaryColor,
          bgColor: Colors.white,
        ),
        child: ListView.builder(
            scrollDirection: Axis.vertical,
            itemCount: _mallGoodsList.length,
            itemBuilder: (BuildContext context, int index) {
              return _listWidgetItem(_mallGoodsList[index]);
            }),
      );
    });
  }
}
